package com.cfweb.api;

import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.cfweb.controller.LoginHandler;
import com.cfweb.pojo.OauthToken;
import com.cfweb.util.CloudFoundryClientUtil;
import com.cfweb.util.JsonUtil;

public class OauthApi {
	
	public static OauthToken login(String username,String password,HttpSession session) throws Exception{
		//构造参数
		Map<String,String> params=new LinkedHashMap<String,String>();
		params.put("grant_type", "password");
		params.put("username", username);
		params.put("password", password);
		
		String host = ((URL)session.getAttribute(LoginHandler.TARGET)).toString();
		host=host.replaceFirst("api", "uaa");
		String response=CloudFoundryClientUtil.doOauth(host+"/oauth/token", params,session);
		Map<String,Object> data=(Map<String, Object>) JsonUtil.convertJsonToMap(response);
		return new OauthToken((String)data.get("access_token"),(String)data.get("token_type"),(String)data.get("refresh_token"),(int)data.get("expires_in"));
	}
	
	public static OauthToken refreshToken(String refreshToken,HttpSession session) throws Exception{
		//构造参数
		Map<String,String> params=new LinkedHashMap<String,String>();
		params.put("grant_type", "refresh_token");
		params.put("refresh_token", refreshToken);
		
		String host = ((URL)session.getAttribute(LoginHandler.TARGET)).toString();
		host=host.replaceFirst("api", "uaa");
		String response=CloudFoundryClientUtil.doOauth(host+"/oauth/token", params,session);
		Map<String,Object> data=(Map<String, Object>) JsonUtil.convertJsonToMap(response);
		return new OauthToken((String)data.get("access_token"),(String)data.get("token_type"),(String)data.get("refresh_token"),(int)data.get("expires_in"));
	}
	
	public static void main(String[] args){
		try {
			OauthToken returns=OauthApi.login("admin", "c1oudc0w",null);
			System.out.println(returns.getAccessToken());
			/*ApplicationApi.updateApplicationMem("fc20137b-4903-47f6-90ab-8ed57f2b7c03",
					1024, null);
			ApplicationApi.stopApplication("fc20137b-4903-47f6-90ab-8ed57f2b7c03", null);
			ApplicationApi.startApplication("fc20137b-4903-47f6-90ab-8ed57f2b7c03", null);*/
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
}
